package cn.cdeden.knowledge.controller.formDoc;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.oss.enumd.OssBucketOneEnum;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.SysFormDocFile;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.TeamFilesTree;
import cn.cdeden.knowledge.domain.dto.SysFormDocFileDto;
import cn.cdeden.knowledge.domain.dto.SysFormDocFileQueryParam;
import cn.cdeden.knowledge.domain.vo.FilesSizeType;
import cn.cdeden.knowledge.enums.FileEnums;
import cn.cdeden.knowledge.enums.StorageTypeEnum;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.resource.api.RemoteFileService;
import cn.cdeden.resource.api.domain.RemoteFileDto;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.model.LoginUser;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author Chen
 * @date 2023-09-11
 **/
@RestController
@RequiredArgsConstructor
//@Api(tags = "表单文档文件管理")
@RequestMapping("/api/sysFormDocFile")
public class SysFormDocFileController {

    private final SysFormDocFileService sysFormDocFileService;

    private final TeamService teamService;

    private final TeamFilesTreeService teamFilesTreeService;

    private final FileService fileService;
    private final PersonalFilesTreeService filesTreeService;

    @DubboReference
    private final RemoteFileService remoteFileService;
    @GetMapping(value = "query")
//    @Log("查询表单文档文件")
//    @ApiOperation("查询表单文档文件")
    public R<TableDataInfo<SysFormDocFileDto>> query(SysFormDocFileQueryParam query, Pageable pageable){
        TableDataInfo<SysFormDocFileDto> info = sysFormDocFileService.queryAll(query,pageable);
        return R.ok(info);
    }

//    @Log("上传表单文档文件")
//    @ApiOperation("上传表单文档文件")
    @ResponseBody
    @PostMapping(value = "/upload")
    public R upload(List<MultipartFile> files ,@RequestParam(value = "sysFormDocFileJson") String sysFormDocFileJson) throws IOException {

        SysFormDocFileDto sysFormDocFileDto = JSONObject.parseObject(sysFormDocFileJson, SysFormDocFileDto.class);
        LoginUser loginUser = LoginHelper.getLoginUser();
        FileEnums enums = null;
        Team team = null;
        if (sysFormDocFileDto.getType().equals("0")||sysFormDocFileDto.getType().equals(TreeEnum.PERSONAL.getType())){
            enums = FileEnums.PERSONAL_FORM_DOC_FILE;
        }else {
            team = teamService.getById(sysFormDocFileDto.getTeamId());
            enums = FileEnums.TEAM_FORM_DOC_FILE;
        }
        //上传文件并获取总共大小
        long totalSize = 0;
        String treeNodeId = sysFormDocFileDto.getTreeNodeId();
        for (MultipartFile file : files) {
//            Storage storage = fileStorageUtils.create(String.valueOf(user.getId()), user.getUsername(), null, file.getOriginalFilename(), StorageFolderTypeEnum.FORM_DOC_FILES.getCode(),file, enums,null);
//            sysFormDocFileDto.setFormDocId(String.valueOf(sysFormDocFileDto.getFormDocId()));
//            sysFormDocFileDto.setStorageId(String.valueOf(storage.getStorageId()));
//            String realName = storage.getRealName();
//            sysFormDocFileDto.setFileName(realName.substring(0,realName.indexOf(".")));
//            sysFormDocFileDto.setSuffix(storage.getSuffix());
//            sysFormDocFileDto.setSize(storage.getSize());
//            sysFormDocFileService.insert(sysFormDocFileDto);
//            totalSize = storage.getSize()+totalSize;


            RemoteFileDto build = RemoteFileDto.builder().name(file.getOriginalFilename())
                .file(file.getBytes())
                .bucketName(OssBucketOneEnum
                    .FORM_DOC_FILES.getCode())
                .originalFilename(file.getOriginalFilename())
                .moduleType(OssModuleType.From_doc).build();
            remoteFileService.upload(build);
        }
        boolean save;
        if (sysFormDocFileDto.getType().equals("0")||sysFormDocFileDto.getType().equals(TreeEnum.PERSONAL.getType())){
            //修改个人的文档大小
            PersonalFilesTree personalFilesTree = filesTreeService.getById(treeNodeId);
            if (null == personalFilesTree.getSize()) {
                personalFilesTree.setSize(totalSize);
            }else {
                personalFilesTree.setSize(personalFilesTree.getSize() + totalSize);
            }
            save = filesTreeService.saveOrUpdate(personalFilesTree);
            fileService.upDateFolderSizeUpDate(String.valueOf(LoginHelper.getUserId()),personalFilesTree,null,totalSize, FilesSizeType.AddSize);  //保存
        }else {
            //修改团队文档大小
            TeamFilesTree teamFilesTree = teamFilesTreeService.getById(treeNodeId);
            if (null == teamFilesTree.getSize()) {
                teamFilesTree.setSize(totalSize);
            }else {
                teamFilesTree.setSize(teamFilesTree.getSize() + totalSize);
            }
            save = teamFilesTreeService.saveOrUpdate(teamFilesTree);
            //修改团队大小
            team.setUsedSpace(team.getUsedSpace() + totalSize);
            teamService.updateById(team);
            teamFilesTreeService.setParentNodeSize(String.valueOf(teamFilesTree.getId()),teamFilesTree.getSize(),0);
        }


        return R.ok(save);
    }
//    @Log("删除表单文档文件")
//    @ApiOperation("删除表单文档文件")
    @ResponseBody
    @GetMapping(value = "/delete")
    public R delete(@RequestParam(value = "id") Integer id) throws IOException {
        SysFormDocFile sysFormDocFile = sysFormDocFileService.getById(id);
        remoteFileService.deleteWithValidByIds(List.of(Long.valueOf(sysFormDocFile.getStorageId())),false);
        return R.ok(sysFormDocFileService.deleteById(id));
    }
}
